<template>
  <el-dialog append-to-body title="案件提交办结" width="45%" top="20px" :visible="visible" @close="handleClose">
    <div class="beautify-scroll white-card">
      <el-form :model="form" :rules="rules" ref="form" label-width="140px">
        <el-form-item label="提交办结类型：" prop="reason">
          <el-select v-model="form.reason" placeholder="请选择" style="width: 100%">
            <el-option v-for="item in optionList" :key="item.id" :label="item.name" :value="item.name"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="提交办结理由：" prop="comment">
          <el-input v-model="form.comment" show-word-limit maxlength="300" placeholder="请输入详细描述" type="textarea" :autosize="{ minRows: 4 }"></el-input>
        </el-form-item>
        <template v-if="hasDebtAmount">
          <el-form-item label="确认欠款金额：" prop="confirmUnPayAmount">
            <el-input-number v-model="form.confirmUnPayAmount" :controls="false" :min="0" placeholder="请输入确认欠款金额"></el-input-number>
            &nbsp;
            <span class="f18">万元</span>
          </el-form-item>
          <el-form-item label="已支付金额：" prop="payedAmount">
            <el-input-number v-model="form.payedAmount" :controls="false" :min="0" placeholder="请输入已支付金额"></el-input-number>
            &nbsp;
            <span class="f18">万元</span>
          </el-form-item>

          <el-form-item label="已还全部欠款：" prop="payAllAmount">
            <el-radio-group v-model="form.payAllAmount">
              <el-radio :label="1" :disabled="payAllAmountRadioDis">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>

          <template v-if="form.payAllAmount === 0">
            <el-row>
              <el-col span="12">
                <el-form-item style="margin-left: 9px" label="" prop="makePayPlan">
                  <el-checkbox v-model="form.makePayPlan" label="已制定还款计划" :true-label="1" :false-label="0"></el-checkbox>
                </el-form-item>
              </el-col>
              <el-col span="12">
                <el-form-item label="已制定支付计划金额：" prop="makePayPlanAmount" label-width="190px">{{ form.makePayPlanAmount }}元</el-form-item>
              </el-col>
            </el-row>
            <template v-if="form.makePayPlan === 1">
              <el-form-item label="还款计划：" prop="payPlanList">
                <el-table v-if="form.payPlanList.length" :data="form.payPlanList" size="mini" border stripe class="repayment-plan-table" style="width: 100%">
                  <el-table-column type="index" label="序号" width="60" align="center"></el-table-column>
                  <el-table-column prop="name" label="还款日期" align="center">
                    <template slot-scope="{ $index }">
                      <el-date-picker v-model="form.payPlanList[$index].planPayTime" value-format="yyyy-MM-dd" type="date" placeholder="请选择还款日期"></el-date-picker>
                    </template>
                  </el-table-column>
                  <el-table-column label="还款金额（万元）" align="center">
                    <template slot-scope="{ $index }">
                      <el-input-number v-model="form.payPlanList[$index].amount" placeholder="请输入还款金额（万元）" :min="1" :controls="false"></el-input-number>
                    </template>
                  </el-table-column>
                  <el-table-column width="100" label="操作" align="center">
                    <template slot-scope="{ $index }">
                      <el-button @click="onDelete($index)" type="primary" plain size="mini">删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
                <el-button @click="onAddRepaymentPlan" type="primary" plain size="mini" style="width: 100%">新增一行</el-button>
              </el-form-item>
            </template>
          </template>

          <el-form-item label="支付备注：" prop="payNote">
            <el-input v-model="form.payNote" show-word-limit maxlength="300" placeholder="请输入支付备注" type="textarea" :autosize="{ minRows: 4 }"></el-input>
          </el-form-item>
        </template>
        <el-form-item label="结案反馈：" prop="satisfactionLevel">
          <el-radio-group v-model="form.satisfactionLevel">
            <el-radio label="satisfaction">满意</el-radio>
            <el-radio label="common">基本满意</el-radio>
            <el-radio label="noSatisfaction">不满意</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 
          源代码：结案报告字段
          2024修改成：结案意见书、结案通知书 需要扩一个字段
        -->
        <el-form-item label="结案意见书：" prop="reportFile">
          <upload-input limitNum="1" :file-list="form.reportFile" :tipsText="'* 需要盖章后上传，支持图片、文档、压缩包格式文件，文件大小不大于 100M'"></upload-input>
        </el-form-item>
        <el-form-item label="结案通知书：" prop="reportNoticeFile">
          <upload-input limitNum="1" :file-list="form.reportNoticeFile" :tipsText="'* 支持图片、文档、压缩包格式文件，文件大小不大于 100M'"></upload-input>
        </el-form-item>

        <el-form-item label="附件：" prop="attachmentFile">
          <upload-input limitNum="1" :file-list="form.attachmentFile" :tipsText="'* 支持图片、文档、压缩包格式文件，文件大小不大于 100M'"></upload-input>
        </el-form-item>
      </el-form>
    </div>
    <div class="split"></div>
    <div class="dialog-footer-btn">
      <el-button @click="handleClose" type="primary" plain>关闭</el-button>
      <el-button @click="handleSubmit" :loading="submitting" type="primary">确定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import * as workOrderApi from "@/api/workOrder/index";
import * as mixins from "@/utils/mixins";
import * as dictApi from "@/api/dict";
import * as templateApi from "@/api/template";
import { extensionName, filename } from "@/utils/filters";
import uploadInput from "@/components/uploadInput/uploadInput.vue";

export default {
  components: { uploadInput },
  name: "completeDialog",
  mixins: [mixins.loading, mixins.form, mixins.dialog, mixins.upload],
  filters: { extensionName, filename },
  props: ["visible", "workOrderNo", "hasDebtAmount", "workOrderId"],
  data() {
    return {
      submitting: false,
      form: {
        payNote: "",
        makePayPlanAmount: undefined,
        payedAmount: undefined,
        payAllAmount: undefined,
        confirmUnPayAmount: undefined,
        makePayPlan: 0,
        reason: "",
        comment: "",
        attachmentFile: [],
        reportFile: [],
        reportNoticeFile: [],
        satisfactionLevel: "",
        payPlanList: [],
      },
      rules: {
        reason: [{ required: true, message: "请选择" }],
        comment: [{ required: true, message: "请填写" }],
        // payNote: [{ required: true, message: "请填写" }],
        makePayPlanAmount: [{ required: true, message: "请填写", trigger: "blur" }],
        payedAmount: [{ required: true, message: "请填写", trigger: "blur" }],
        confirmUnPayAmount: [{ required: true, message: "请填写", trigger: "blur" }],
        reportFile: [{ required: true, message: "请上传" }],
        reportNoticeFile: [{ required: true, message: "请上传" }],
        satisfactionLevel: [{ required: true, message: "请选择" }],
        payAllAmount: [{ required: true, message: "请选择" }],
        payPlanList: [
          { required: true, message: "请填写" },
          {
            validator(rule, value, callback) {
              const errorNumbers = [];
              value.forEach((item, i) => {
                if (!(item.planPayTime && item.amount)) {
                  errorNumbers.push(i + 1);
                }
              });
              if (errorNumbers.length) {
                callback(new Error(`请设置序号 ${errorNumbers.join(",")} 的还款日期和还款金额`));
                return;
              }
              callback();
            },
            trigger: "blur",
          },
        ],
      },
      optionList: [],
      reportFileUploading: false,
      attachmentFileUploading: false,
    };
  },
  watch: {
    "form.payPlanList": {
      handler() {
        this.form.makePayPlanAmount = this.form.payPlanList.reduce((total, item) => {
          return total + (item.amount || 0);
        }, 0);
      },
      deep: true,
      immediate: true,
    },
    "form.payAllAmount"(val) {
      if (val === 1) {
        this.form.makePayPlan = 0;
        this.form.payPlanList = [];
      }
    },
    "form.makePayPlan"(val) {
      if (val === 0) {
        this.form.payPlanList = [];
      } else {
        this.onAddRepaymentPlan();
      }
    },
  },
  computed: {
    payAllAmountRadioDis() {
      let disabled = false;
      if (this.form.payedAmount && this.form.confirmUnPayAmount && this.form.confirmUnPayAmount > this.form.payedAmount) {
        disabled = true;
        this.form.payAllAmount = undefined;
      } else {
        disabled = false;
      }
      return disabled;
    },
  },
  mounted() {},
  methods: {
    show() {
      dictApi.list({ parentCode: "1005" }).then((res) => {
        this.optionList = res.result;
      });

      templateApi.detailByCode(1009).then((res) => {
        this.form.comment = res.result.value;
      });

      this.$nextTick(() => {
        // this.bindFileChangeEvent('reportFile', 1)
        // this.bindFileChangeEvent('attachmentFile', 1)
      });
    },
    handleSubmit() {
      this.validateAndConfirm("form", "确定要提交办结该案件么？")
        .then(() => {
          this.submitting = true;

          const form = {
            ...this.form,
            attachmentFile: this.form.attachmentFile[0],
            reportFile: this.form.reportFile[0],
            reportNoticeFile: this.form.reportNoticeFile[0],
            workOrderNo: this.workOrderNo,
            payPlanList: this.form.payPlanList.map((item) => {
              item.workOrderId = this.workOrderId;
              return item;
            }),
          };
          return workOrderApi.process.finishProcess(form);
        })
        .then(() => {
          this.$emit("success");
          this.handleClose();
        })
        .finally(() => (this.submitting = false));
    },
    onAddRepaymentPlan() {
      this.form.payPlanList.push({
        planPayTime: undefined,
        amount: undefined,
      });
    },
    onDelete(index) {
      if (this.form.payPlanList.length === 1) {
        return this.$message.error("至少保留一条还款计划");
      }
      this.form.payPlanList.splice(index, 1);
      this.$nextTick(() => {
        this.validateField("form", "payPlanList");
      });
    },
  },
};
</script>

<style lang="less" scoped>
.tips {
  text-align: center;
  margin-bottom: 20px;
}

.beautify-scroll {
  max-height: 70vh;
}
/deep/.el-radio__input {
  transform: scale(1.1);
}
/deep/.el-radio__label {
  font-size: 16px;
}
</style>

<style lang="less">
.repayment-plan-table {
  .el-input__inner {
    border: none;
    background: transparent;
    //padding: 0;
  }

  //&.el-table .cell {
  //  padding: 0;
  //}

  .el-input__inner:hover,
  .el-input__inner:focus {
    border: none;
  }

  &.el-table--enable-row-hover .el-table__body tr:hover > td {
    background-color: inherit !important;
  }

  &.el-table--enable-row-hover .el-table__body tr:hover > td .cell {
    color: inherit;
  }

  .el-input-number {
    width: 100%;
  }
}

.el-input-number .el-input__inner {
  text-align: left;
  padding: 0;
}
</style>
